﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace PersonaLibrary
{
	internal class Metadata
	{
		private static Metadata _instance;

		private Dictionary<string, List<Point>> _points;

		private Metadata()
		{
			_points = new Dictionary<string, List<Point>>();
		}

		public List<Point> this[string typeName]
		{
			get
			{
				List<Point> result;
				if (!_points.TryGetValue(typeName, out result))
				{
					result = InitPoints(typeName);
					if(result != null)
						_points.Add(typeName, InitPoints(typeName));
				}

				return result;
			}
		}

		private List<Point> InitPoints(string typeName)
		{
			XDocument metaDoc = XDocument.Load("Config\\Metadata.xml");

			IEnumerable<XElement> elements = metaDoc.Element("root").Elements("type");

			XElement element = elements.FirstOrDefault(x => x.Attribute("name").Value == typeName);

			if (element != null)
			{

				IEnumerable<XElement> pointElements = element.Elements("point");
				List<Point> result = pointElements.Select(x => new Point
				                                               	{
				                                               		Name = Convert.ToString(x.Element("name").Value),
				                                               		RuName = Convert.ToString(x.Element("ruName").Value),
				                                               		IsOrder = Convert.ToBoolean(x.Element("isOrder").Value),
				                                               		IsFilter = Convert.ToBoolean(x.Element("isFilter").Value),
				                                               	}).ToList();

				return result;
			}

			return null;
		}

		public static Metadata Instance
		{
			get
			{
				if(_instance == null)
					_instance = new Metadata();
				return _instance;
			}
		}

		public class Point
		{
			public string Name { internal set; get; }
			public string RuName { internal set; get; }
			public bool IsOrder { internal set; get; }
			public bool IsFilter { internal set; get; }
		}
	}
}
